package com.cby.code.net.task;

import com.cby.code.net.Request;
import com.cby.code.net.Response;
import com.cby.code.net.policy.RetryPolicy;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;

/**
 * @description: HttpUrlFileTask
 * @author: ChenBaoYang
 * @createDate: 2022/3/8 4:09 下午
 */
public class HttpUrlDownloadFileTask extends BaseTask {


    @Override
    public Response performRequest(Request request) {
        HttpURLConnection connection = null;
        try {
            // 创建连接
            connection = createConnection(request);
            // 设置请求头
            setHeaders(connection, request.getParam());
            // 设置请求参数和请求方式
            setConnectionParametersForRequest(connection, request);
            // 解析相应数据
            return parseResponseFile(connection, request);
        } catch (Exception e) {
            RetryPolicy policy = request.getRetryPolicy();
            if (policy != null) {
                policy.retry(e);
            }
        } finally {
            closeConnection(connection);
        }
        return null;
    }

    /**
     * 处理下载的文件
     *
     * @param connection
     */
    public Response parseResponseFile(HttpURLConnection connection, Request request) throws IOException {
        int httpStatus = connection.getResponseCode();
        if (isOK(httpStatus)) {
            String filePath = request.getFilePath();
            File descFile = new File(filePath);
            FileOutputStream fos = new FileOutputStream(descFile);
            ;
            byte[] buffer = new byte[1024];
            int len;
            InputStream inputStream = connection.getInputStream();
            while ((len = inputStream.read(buffer)) != -1) {
                // 写到本地
                fos.write(buffer, 0, len);
            }
            fos.close();
            return new Response(filePath, httpStatus, "");
        } else {
            return new Response(null, httpStatus, connection.getResponseMessage());
        }
    }



}
